package com.bsoft.gol.hbs.message.sendMsg;

import ctd.spring.boot.annotation.SsdevService;
import ctd.util.annotation.RpcService;
import hcn.bean.MsgTemplateDTO;
import hcn.bean.PushMessageBean;
import hcn.bean.SendMsgDTO;
import hcn.util.BaseResponse;
import hcn.service.base.sendMsg.IISendMsgService;
import org.springframework.stereotype.Service;


/**
 * @description: 发送消息接口实现
 * @author: zhengcb10708
 * @create: 2020-09-24 19:12
 **/
@SsdevService("sendMsgService")
public class SendMsgServiceImpl implements IISendMsgService {

    @Override
    @RpcService
    public BaseResponse sendMsg(SendMsgDTO sendMsgDTO, MsgTemplateDTO msgTemplateDTO) {
        return null;
    }

    @Override
    @RpcService
    public BaseResponse sendPushMsg(PushMessageBean pushMessageBean) {
        return null;
    }

   /* private final static Logger logger = LoggerFactory.getLogger(SendMsgServiceImpl.class);
    @Autowired
    private IMsgManageService msgManageService;
    @Autowired
    private UserPreferenceDAO userPreferenceDAO;
    @Autowired
    private MsgPushTaskDao msgPushTaskDao;
    private AbstractSendMsgServiceImpl abtSendMsgService;
   // @Value("${wechat_name}")
    private String wechatName="Bsoft健康通微信号云平台";

    public AbstractSendMsgServiceImpl getAbtSendMsgService() {
        return abtSendMsgService;
    }

    public void setAbtSendMsgService(AbstractSendMsgServiceImpl abtSendMsgService) {
        this.abtSendMsgService = abtSendMsgService;
    }

    *//**
     * @Describe: 发送消息服务
     * @Param: [sendMsgDTO, msgTemplateDTO]
     * @Return: BaseResponse
     * @Author: zhengcb10708
     * @Date: 2020/9/24 19:35
     *//*
    @RpcService
    @Override
    public BaseResponse sendMsg(SendMsgDTO sendMsgDTO, MsgTemplateDTO msgTemplateDTO) {
        BaseResponse baseResponse = new BaseResponse();
        MsgManageDetailVo msgManageDetailVo = null;
        BaseResponse<MsgManageDetailVo> MsgManageDetailVoBaseResponse = null;
        try {
            //默认租户id
            if(CommonUtils.isNull(msgTemplateDTO.getTenantId())){
                msgTemplateDTO.setTenantId(RpcUserToken.getTenantId());
            }

            if (CommonUtils.isNotNull(msgTemplateDTO.getMsgTemplateId())) {
                MsgManageDetailQo msgManageDetailQo = new MsgManageDetailQo();
                msgManageDetailQo.setMsgTemplateId(msgTemplateDTO.getMsgTemplateId());
                msgManageDetailVo= msgManageService.detail(msgManageDetailQo);
            } else if (CommonUtils.isNotNull(msgTemplateDTO.getTemplateCode())) {
                msgManageDetailVo = msgManageService.detailByTempCodeAndTenantId(msgTemplateDTO.getTemplateCode(), msgTemplateDTO.getTenantId());
            }else if(CommonUtils.isNotNull(msgTemplateDTO.getNotificateType())){
                msgManageDetailVo = msgManageService.detailByNotificateTypeAndTenantId(msgTemplateDTO.getNotificateType(), msgTemplateDTO.getTenantId());
            }else if(CommonUtils.isNotNull(msgTemplateDTO.getSmsserviceType())){
                msgManageDetailVo = msgManageService.detailBySmsServiceTypeAndTenantId(msgTemplateDTO.getSmsserviceType(), msgTemplateDTO.getTenantId());
            }
            if (msgManageDetailVo != null) {
                String noticeType = msgManageDetailVo.getNoticeType();
                sendMsgDTO.setDicCode(noticeType);
                sendMsgDTO.setLinkType(msgManageDetailVo.getLinkType());
                if(CommonUtils.isNull(sendMsgDTO.getMsgTitle())){
                    sendMsgDTO.setMsgTitle(msgManageDetailVo.getMsgTitle());
                }
                sendMsgDTO.setSmsTemplateId(msgManageDetailVo.getSmsTemplateId());
                sendMsgDTO.setSmsJumpUrl(msgManageDetailVo.getSmsJumpUrl());
                //消息主体内容
                String content = msgManageDetailVo.getTemplateContent();
                //消息体内容处理
                content = handleContent(sendMsgDTO, msgTemplateDTO, msgManageDetailVo, content);
                List<String> msgTemplateMsgTypeList = msgManageDetailVo.getMsgTemplateMsgTypeList();
                if (CommonUtils.isNotEmpty(msgTemplateMsgTypeList)) {
                    if (MsgNoticeType.getEnumByKey(noticeType) != null) {
                        //根据消息开关设置处理消息发送的渠道
                        handleMsgTypeListBySetting(sendMsgDTO, msgTemplateMsgTypeList, noticeType);
                    } else {
                        //没有类型的默认其他类型
                        sendMsgDTO.setDicCode(MsgNoticeType.OTHER.getType());
                    }
                    List<ISendMsgService> sendMsgServiceImpls = SendMsgServiceImplsFactory.getSendMsgServiceImpls
                            (msgTemplateMsgTypeList);
                    if (CommonUtils.isNotEmpty(sendMsgServiceImpls)) {
                        StringBuilder message = new StringBuilder();
                        boolean haveSuccess = false;
                        MsgTemplateWxConfigure templateWxConfigure = msgManageDetailVo.getTemplateWxConfigure();
                        for (ISendMsgService sendMsgService :
                                sendMsgServiceImpls) {
                            //这里需要每次清空 WeChatTextMap ，避免出现脏数据
                            if(CommonUtils.isNotNull(sendMsgDTO.getWeChatTextMap())){
                                sendMsgDTO.getWeChatTextMap().isEmpty();
                            }
                            //发送微信公众号模板消息的消息入参处理
                            if (MsgType.WECHAT.getMsgTypeKey().equals(sendMsgService.getMsgType())
                                    && templateWxConfigure != null
                                    && StringUtils.hasText(templateWxConfigure.getSubscriptionTemplateId())) {
                                Map<String,String> weChatTextMap= new HashMap<String, String>();
                                sendMsgDTO.setWeChatTplCode(templateWxConfigure.getSubscriptionTemplateCode());
                                if(CommonUtils.isEmpty(sendMsgDTO.getAppId())){//如果传值appId为空,则取数据库配置的appid
                                    sendMsgDTO.setAppId(templateWxConfigure.getAppId());
                                }
                                if (StringUtils.hasText(templateWxConfigure.getSubscriptionFirst())) {
                                    weChatTextMap.put("first",handleConfigureVariable(templateWxConfigure.getSubscriptionFirst(),
                                            msgTemplateDTO.getMsgVariableList()));
                                } else {
                                    weChatTextMap.put("first", "");
                                }
                                weChatTextMap.put("first_color",
                                        templateWxConfigure.getSubscriptionFirstColor());
                                if (StringUtils.hasText(templateWxConfigure.getSubscriptionKeyword1())) {
                                    weChatTextMap.put("keyword1",handleConfigureVariable(templateWxConfigure.getSubscriptionKeyword1(),
                                            msgTemplateDTO.getMsgVariableList()));
                                } else {
                                    weChatTextMap.put("keyword1", "");
                                }
                                weChatTextMap.put("keyword1_color",
                                        templateWxConfigure.getSubscriptionKeyword1Color());
                                if (StringUtils.hasText(templateWxConfigure.getSubscriptionKeyword2())) {
                                    weChatTextMap.put("keyword2",handleConfigureVariable(templateWxConfigure.getSubscriptionKeyword2(),
                                            msgTemplateDTO.getMsgVariableList()));
                                } else {
                                    weChatTextMap.put("keyword2", "");
                                }
                                weChatTextMap.put("keyword2_color",
                                        templateWxConfigure.getSubscriptionKeyword2Color());
                                if (WhetherEnum.YES.getKey().equals(templateWxConfigure.getSubscriptionKeyword3Flag())) {
                                    if (StringUtils.hasText(templateWxConfigure.getSubscriptionKeyword3())) {
                                        weChatTextMap.put("keyword3",handleConfigureVariable(templateWxConfigure.getSubscriptionKeyword3(),
                                                msgTemplateDTO.getMsgVariableList()));
                                    } else {
                                        weChatTextMap.put("keyword3", "");
                                    }
                                    weChatTextMap.put("keyword3_color",
                                            templateWxConfigure.getSubscriptionKeyword3Color());
                                }
                                if (WhetherEnum.YES.getKey().equals(templateWxConfigure.getSubscriptionKeyword4Flag())) {
                                    if (StringUtils.hasText(templateWxConfigure.getSubscriptionKeyword4())) {
                                        weChatTextMap.put("keyword4",handleConfigureVariable(templateWxConfigure.getSubscriptionKeyword4(),
                                                msgTemplateDTO.getMsgVariableList()));
                                    } else {
                                        weChatTextMap.put("keyword4", "");
                                    }
                                    weChatTextMap.put("keyword4_color",
                                            templateWxConfigure.getSubscriptionKeyword4Color());
                                }
                                if (WhetherEnum.YES.getKey().equals(templateWxConfigure.getSubscriptionKeyword5Flag())) {
                                    if (StringUtils.hasText(templateWxConfigure.getSubscriptionKeyword5())) {
                                        weChatTextMap.put("keyword5",handleConfigureVariable(templateWxConfigure.getSubscriptionKeyword5(),
                                                msgTemplateDTO.getMsgVariableList()));
                                    } else {
                                        weChatTextMap.put("keyword5", "");
                                    }
                                    weChatTextMap.put("keyword5_color",
                                            templateWxConfigure.getSubscriptionKeyword5Color());
                                }
                                if (StringUtils.hasText(templateWxConfigure.getSubscriptionRemark())) {
                                    weChatTextMap.put("remark",handleConfigureVariable(templateWxConfigure.getSubscriptionRemark(),
                                            msgTemplateDTO.getMsgVariableList()));
                                } else {
                                    weChatTextMap.put("remark", "");
                                }
                                weChatTextMap.put("remark_color",
                                        templateWxConfigure.getSubscriptionRemarkColor());
                                sendMsgDTO.setWeChatTextMap(weChatTextMap);

                            }

                            BaseResponse oneBaseResponse = sendMsgService.sendMsg(sendMsgDTO, content);
                            if (oneBaseResponse.getCode() != ResultCode.SUCCESS) {
                                message.append(oneBaseResponse.getMessage() + "\t");
                            } else {
                                haveSuccess = true;
                            }
                        }
                        if (haveSuccess) {
                            baseResponse.setCode(ResultCode.SUCCESS);
                            if (message.toString().trim().length() > 0) {
                                logger.warn("消息发送失败,{},{}", sendMsgDTO, message);
                                baseResponse.setMessage(message + "\t" + "其他类型消息发送成功");
                            } else {
                                baseResponse.setMessage("消息发送成功");
                            }
                        } else {
                            logger.warn("消息发送失败,{},{}", sendMsgDTO, msgTemplateDTO);
                            baseResponse.setCode(ResultCode.ERROR);
                            baseResponse.setMessage("消息发送失败");
                        }
                    }
                } else {
                    logger.warn("消息模板对应的消息类型列表为空,无法完成消息发送操作,{}", msgTemplateDTO);
                    baseResponse.setCode(ResultCode.ERROR);
                    baseResponse.setMessage("消息模板对应的消息类型列表为空,无法完成消息发送操作");
                }
            } else {
                logger.warn("对应的消息模板未找到,无法完成消息发送操作,{}", msgTemplateDTO);
                baseResponse.setCode(ResultCode.ERROR);
                baseResponse.setMessage("对应的消息模板未找到,无法完成消息发送操作");
            }
        } catch (Exception e){

        }
        return baseResponse;
    }
    *//**
     * @Describe: 发送手工推送消息
     * @Param: [pushMessageBean]
     * @Return: BaseResponse
     * @Author: zhengcb10708
     * @Date: 2021/9/8 9:52
     *//*
    @Override
    public BaseResponse sendPushMsg(PushMessageBean pushMessageBean) {
        BaseResponse baseResponse = new BaseResponse();
        SendMsgDTO sendMsgDTO = new SendMsgDTO();
        MsgPushTask msgPushTask=msgPushTaskDao.getMsgPushTaskByTaskId(pushMessageBean.getUid());
        if(msgPushTask!=null&&CommonUtils.isNotEmpty(msgPushTask.getMsgType())){
            pushMessageBean.setUid(msgPushTask.getMsgPushTaskId());
            pushMessageBean.setMsgTitle(msgPushTask.getMsgTitle());
            BeanUtils.copyProperties(pushMessageBean,sendMsgDTO);
            String content=msgPushTask.getContent();
            //获取到消息的发送类型
            List<String> msgTypeList = Arrays.asList(msgPushTask.getMsgType().split(","));
            List<ISendMsgService> sendMsgServiceImpls = SendMsgServiceImplsFactory.getSendMsgServiceImpls
                    (msgTypeList);
            boolean haveSuccess = false;
            StringBuilder message = new StringBuilder();
            if(CommonUtils.isNotEmpty(sendMsgServiceImpls)){
                for (ISendMsgService sendMsgService : sendMsgServiceImpls){
                    BaseResponse oneBaseResponse = sendMsgService.sendPushMsg(sendMsgDTO, content);
                    if (oneBaseResponse.getCode() != ResultCode.SUCCESS) {
                        message.append(oneBaseResponse.getMessage() + "\t");
                    } else {
                        haveSuccess = true;
                    }
                }
            }
            if (haveSuccess) {
                baseResponse.setCode(ResultCode.SUCCESS);
                if (message.toString().trim().length() > 0) {
                    logger.warn("消息发送失败,{},{}", sendMsgDTO, message);
                    baseResponse.setMessage(message + "\t" + "其他类型消息发送成功");
                } else {
                    baseResponse.setMessage("消息发送成功");
                }
            } else {
                logger.warn("消息发送失败,{},{}", sendMsgDTO);
                baseResponse.setCode(ResultCode.ERROR);
                baseResponse.setMessage("消息发送失败");
            }
        }
        return baseResponse;
    }

    *//**
     * @Describe: 根据消息开关设置处理消息发送的渠道
     * @Param: [sendMsgDTO, msgTemplateMsgTypeList, noticeType]
     * @Return: void
     * @Author: zhengcb10708
     * @Date: 2020/9/25 14:27
     *//*
    private void handleMsgTypeListBySetting(SendMsgDTO sendMsgDTO, List<String> msgTemplateMsgTypeList,
                                            String noticeType) {
        if (CommonUtils.isNotNull(sendMsgDTO.getUserId())&&CommonUtils.isNotNull(sendMsgDTO.getRoleId())) {
            //默认租户id
            if(CommonUtils.isNull(sendMsgDTO.getTenantId())){
                sendMsgDTO.setTenantId(RpcUserToken.getTenantId());
            }

            UserPreference userPreference= userPreferenceDAO.getByUserIdAndRoleId(sendMsgDTO.getTenantId(),sendMsgDTO.getUserId(),sendMsgDTO.getRoleId());
            if (CommonUtils.isNotNull(userPreference)) {
                //先判断全局开关
                if (SwitchStatus.OFF.getStatus().equals(userPreference.getGlobalSwitch())) {
                    //关闭除APP内置消息之外其他消息
                    closeOtherMsgType(msgTemplateMsgTypeList);
                } else {
                    //判断业务消息开关
                    if (StringUtils.hasText(noticeType)) {
                        boolean off = false;
                        MsgNoticeType enumByKey = getEnumByKey(noticeType);
                        if (enumByKey != null) {
                            switch (enumByKey) {
                                case SYSTEM:
                                    if (SwitchStatus.OFF.getStatus().equals(userPreference.getSystemSwitch())) {
                                        off = true;
                                    }
                                    break;
                                case INTERNET:
                                    if (SwitchStatus.OFF.getStatus().equals(userPreference.getInternetTreat())) {
                                        off = true;
                                    }
                                    break;
                                case OFFLINE:
                                    if (SwitchStatus.OFF.getStatus().equals(userPreference.getOfflineService())) {
                                        off = true;
                                    }
                                    break;
                                case PAY:
                                    if (SwitchStatus.OFF.getStatus().equals(userPreference.getPayInform())) {
                                        off = true;
                                    }
                                    break;
                                case ORDER:
                                    if (SwitchStatus.OFF.getStatus().equals(userPreference.getOrderRemind())) {
                                        off = true;
                                    }
                                    break;
                                case REPORT:
                                    if (SwitchStatus.OFF.getStatus().equals(userPreference.getReportRemind())) {
                                        off = true;
                                    }
                                    break;
                                case MSQ:
                                    if (SwitchStatus.OFF.getStatus().equals(userPreference.getMsqInpect())) {
                                        off = true;
                                    }
                                    break;
                                default:
                                    break;
                            }
                        }
                        if (off) {
                            //关闭除APP内置消息之外其他消息
                            closeOtherMsgType(msgTemplateMsgTypeList);
                        }
                    }
                }
                //判断滚动消息开关
                if (SwitchStatus.OFF.getStatus().equals(userPreference.getScrollRemind())) {
                    for (int i = 0; i < msgTemplateMsgTypeList.size(); ) {
                        String msgType = msgTemplateMsgTypeList.get(i);
                        //只要关闭了就关闭滚动消息(待办事项)
                        if (MsgType.PENDING_EVENT.getMsgTypeKey().equals(msgType)) {
                            msgTemplateMsgTypeList.remove(i);
                        } else {
                            i++;
                        }
                    }
                }
                //判断声音开关
                //极光文档：部分手机受手机系统限制可能无法达到效果
                if (SwitchStatus.OFF.getStatus().equals(userPreference.getSoundSwitch())) {
                    sendMsgDTO.setSound(false);
                } else {
                    sendMsgDTO.setSound(true);
                }
                //判断振动开关
                //极光文档：部分手机受手机系统限制可能无法达到效果
                if (SwitchStatus.OFF.getStatus().equals(userPreference.getVibrateSwitch())) {
                    sendMsgDTO.setVibrate(false);
                } else {
                    sendMsgDTO.setVibrate(true);
                }
            }
        }
    }

   *//**
    * @Describe: 关闭除APP内置消息之外其他消息
    * @Param: [msgTemplateMsgTypeList]
    * @Return: void
    * @Author: zhengcb10708
    * @Date: 2020/9/25 14:27
    *//*
    private void closeOtherMsgType(List<String> msgTemplateMsgTypeList) {
        for (int i = 0; i < msgTemplateMsgTypeList.size(); ) {
            String msgType = msgTemplateMsgTypeList.get(i);
            //只要关闭了就关闭除APP内置消息之外的所有消息
            if (!MsgType.PENDING_EVENT.getMsgTypeKey().equals(msgType) &&
                    !MsgType.APP_MESSAGE_PAGE.getMsgTypeKey().equals(msgType)) {
                msgTemplateMsgTypeList.remove(i);
            } else {
                i++;
            }
        }
    }

    *//**
     * @Describe: 消息体内容处理
     * @Param: [sendMsgDTO, msgTemplateDTO, msgManageDetailVo, content]
     * @Return: java.lang.String
     * @Author: zhengcb10708
     * @Date: 2020/9/25 13:59
     *//*
    private String handleContent(SendMsgDTO sendMsgDTO, MsgTemplateDTO msgTemplateDTO,
                                 MsgManageDetailVo msgManageDetailVo, String content) {
        //跳转url
        String linkTarget = msgManageDetailVo.getLinkTarget();
        List<MsgVariableQo> msgVariableList = msgTemplateDTO.getMsgVariableList();
        //遍历消息体变量列表，进行变量赋值
        if (!CollectionUtils.isEmpty(msgVariableList)) {
            //处理短信变量列表
            boolean handleSMSParameter = false;
            JSONObject smsParameter = new JSONObject();
            if (StringUtils.hasText(msgManageDetailVo.getSmsParameterList())) {
                try {
                    handleSMSParameter = true;
                    smsParameter = JSON.parseObject(msgManageDetailVo.getSmsParameterList());
                } catch (Exception e) {
                    handleSMSParameter = false;
                }
            }
            for (MsgVariableQo msgVariableQo :
                    msgVariableList) {
                if (msgVariableQo.getMsgVariableKey() != null) {
                    if (handleSMSParameter) {
                        for (Map.Entry<String, Object> entry :
                                smsParameter.entrySet()) {
                            if (msgVariableQo.getMsgVariableKey().equals(entry.getValue())) {
                                smsParameter.put(entry.getKey(), msgVariableQo.getMsgVariableValue() == null ?
                                        "" :
                                        msgVariableQo.getMsgVariableValue());
                            }
                        }
                    }
                    content = content.replaceAll(msgVariableQo.getMsgVariableKey(),
                            msgVariableQo.getMsgVariableValue() == null ? "" :
                                    msgVariableQo.getMsgVariableValue());
                    linkTarget = linkTarget.replaceAll(msgVariableQo.getMsgVariableKey(),
                            msgVariableQo.getMsgVariableValue() == null ? "" :
                                    msgVariableQo.getMsgVariableValue());
                }
            }
            if (handleSMSParameter) {
                sendMsgDTO.setSmsParameterList(smsParameter);
            }
        }
        sendMsgDTO.setLinkTarget(linkTarget);
        //如果消息体里面附带url变量的，替换已经拼接好的url
        if (content.contains(MsgVariable.URL.getMsgVariableKey()) && StringUtils.hasText(linkTarget)) {
            content = content.replaceAll(MsgVariable.URL.getMsgVariableKey(), linkTarget);
        }
        //替换微信公众号名称
        if (content.contains(MsgVariable.WECHAT_NAME.getMsgVariableKey())) {
            content = content.replaceAll(MsgVariable.WECHAT_NAME.getMsgVariableKey(), wechatName);
        }
        return content;
    }
    *//**
     * @Describe: 处理配置里面的变量信息
     * @Param: [configureKeyword, msgVariableList]
     * @Return: java.lang.String
     * @Author: zhengcb10708
     * @Date: 2020/10/16 15:25
     *//*
    private String handleConfigureVariable(String configureKeyword, List<MsgVariableQo> msgVariableList) {
        //遍历消息体变量列表，进行变量赋值
        if (!CollectionUtils.isEmpty(msgVariableList) && StringUtils.hasText(configureKeyword)) {
            for (MsgVariableQo msgVariableQo :
                    msgVariableList) {
                //这里处理变量只处理##【】包裹的，避免出现非变量文本被替换
                String msgVariableKey = msgVariableQo.getMsgVariableKey();
                if (msgVariableKey != null
                        && ((msgVariableKey.startsWith("#") && msgVariableKey.endsWith("#")) || (msgVariableKey.startsWith("【") && msgVariableKey.endsWith("】")))) {
                    configureKeyword = configureKeyword.replaceAll(msgVariableKey,
                            msgVariableQo.getMsgVariableValue() == null ? "" :
                                    msgVariableQo.getMsgVariableValue());

                }
            }
        }
        return configureKeyword;
    }*/
}
